//
//  LocationProfile.m
//  playSerengetiMobile1
//
//  Created by Lita Gratrix on 12/11/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "LocationProfile.h"
#import "JSON/JSON.h"
	
#define kViewTag			1		//for tagging our embedded controls for removal at cell recycle time
#define kTeamsSection		0		//for selecting the table section containing competing Friends

#define ROW_HEIGHT_FOR_TABLE 30

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";

@implementation LocationProfile

@synthesize locationId;
@synthesize locationNameLabel, addressLineOneLabel, addressLineTwoLabel, phoneNumberLabel, teamLeaderLabel, locationProfileTableView;
@synthesize profile, competingTeams;
@synthesize tableSourceArray, appDelegate;

- (void)viewDidLoad{
	[super viewDidLoad];
	
//	NSLog(@"Entering LocationProfile viewDidLoad\n");
//	NSLog(@"LocationProfile.locationId is %d\n", locationId);
	
	self.appDelegate = (playSerengetiMobile1AppDelegate *)[[UIApplication sharedApplication] delegate];
	
	responseData = [[NSMutableData data] retain];
	NSString *URLString = [NSString stringWithFormat:@"%@location/%d/json", appDelegate.baseURL, locationId];
//	NSLog(@"Submit string for LocationProfile is %@\n", URLString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];
	
	self.competingTeams = [[NSMutableArray alloc] init];
	self.tableSourceArray = [NSArray arrayWithObjects:
							 [NSDictionary dictionaryWithObjectsAndKeys:
							  @"Competing Teams", kSectionTitleKey,
							  self.competingTeams, kSourceKey,
							  nil],
							 nil];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark populateViewData Methods

- (void)populateViewData:(NSDictionary *)parsedData{
//	NSLog(@"Entering LocationProfile populateViewData\n");
	profile = [[Location alloc] init];
	profile.locationId = [[parsedData objectForKey:@"id"] integerValue];
	profile.locationName = [parsedData objectForKey:@"name"];
	profile.phoneNumber = [parsedData objectForKey:@"phoneNumber"];
	profile.latitude = [[parsedData objectForKey:@"latitude"] doubleValue];
	profile.longitude = [[parsedData objectForKey:@"longitude"] doubleValue];
	profile.street = [parsedData objectForKey:@"street"];
	profile.city = [parsedData objectForKey:@"city"];
	profile.state = [parsedData objectForKey:@"state"];
	profile.zipCode = [parsedData objectForKey:@"zipcode"];
	profile.description = [parsedData objectForKey:@"description"];
	NSString *teamOwnerName = [[NSString alloc] init];
	teamOwnerName = [parsedData objectForKey:@"owner"]; 
//	NSLog(@"teamOwnerName is %@, parsedData objectForKey:owner is %@\n", teamOwnerName, [parsedData objectForKey:@"owner"]);
	locationNameLabel.text = profile.locationName;
	NSString *tempString = [NSString stringWithFormat:@"%@, %@ %@", profile.city, profile.state, profile.zipCode];
	addressLineOneLabel.text = profile.street;
	addressLineTwoLabel.text = tempString;
	phoneNumberLabel.text = [NSString stringWithFormat:@"Phone Number:%@", profile.phoneNumber];
	teamLeaderLabel.text = [NSString stringWithFormat:@"Team Owner: %@", teamOwnerName];
	NSMutableArray *competingTeamsArray = [[NSMutableArray alloc] init];
	competingTeamsArray = [parsedData objectForKey:@"competingTeams"];
	[self populateCompetingTeams:competingTeamsArray];
	
	[self.locationProfileTableView reloadData];
}

- (void)populateCompetingTeams:(NSMutableArray *)competingTeamsArray{
//	NSLog(@"Entering populateCompetingTeams\n");
	if([competingTeamsArray count] == 0){
		//Do Something
	} else {
		[competingTeams removeAllObjects];
		int i;
		for(i = 0; i < [competingTeamsArray count]; i++){
			Team *aTeam = [[Team alloc] init];
			NSDictionary *teamDic = [competingTeamsArray objectAtIndex:i];
			aTeam.teamId = [[teamDic objectForKey:@"id"] integerValue];
			aTeam.teamName = [teamDic objectForKey:@"name"];
			[competingTeams addObject:aTeam];
		}
//	NSLog(@"competingTeams had %d elements", [competingTeams count]);
	}
	
}
	
#pragma mark -
#pragma mark NSURLConnectionDelegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	locationNameLabel.text = [NSString stringWithFormat:@"Connection failed: %@\n", [error description]];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];
	
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//	NSLog(@"responseString reads: %@\n", responseString);
	
	[responseData release];
	
	NSDictionary *parsedData = [responseString JSONValue];
	
	[responseString release];
	
	if (parsedData == nil) {
		locationNameLabel.text = [NSString stringWithFormat:@"Error in returned data.\n"];
	} else {
		[self populateViewData:(NSDictionary *)parsedData];
	}
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [tableSourceArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[self.tableSourceArray objectAtIndex: section] valueForKey:kSectionTitleKey];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	//	NSLog(@"Entering tableView:%@ numberOfRowsInSection:%d", tableView, section);
	NSMutableArray *sectionData = [[self.tableSourceArray objectAtIndex:section] valueForKey:kSourceKey];
	//	NSLog(@"number of expected rows: %d.\n", [sectionData count]);
	return [sectionData count];
}

// to determine specific row height for each cell, override this.
// In this example, each row is determined by its subviews that are embedded.
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return ROW_HEIGHT_FOR_TABLE;
	//return ([indexPath row] == 0) ? 50.0 : 38.0;
}

// to determine which UITableViewCell to be used on a given row.
//
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//	NSLog(@"Entering cellForRowAtIndexPath\n");
	UITableViewCell *cell = nil;
	Team *aTeam;
	aTeam = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	
	static NSString *kDisplayCell_ID = @"DisplayCellID";
	cell = [self.locationProfileTableView dequeueReusableCellWithIdentifier:kDisplayCell_ID];
	if (cell == nil){
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDisplayCell_ID] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	} else {
		// the cell is being recycled, remove old embedded controls
		UIView *viewToRemove = nil;
		viewToRemove = [cell.contentView viewWithTag:kViewTag];
		if (viewToRemove){
			[viewToRemove removeFromSuperview];
		}
	}
	
	UIControl *control = [[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kViewKey];
	[cell.contentView addSubview:control];
	cell.textLabel.text = aTeam.teamName;
	
	return cell;
}

- (void)switchAction:(id)sender
{
	// NSLog(@"switchAction: value = %d", [sender isOn]);
}

- (void)pageAction:(id)sender
{
	// NSLog(@"pageAction: current page = %d", [sender currentPage]);
}

#pragma mark -
#pragma mark UITableViewDelegate

// the table's selection has changed, switch to that item's UIViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	Team *aTeam;
	
	aTeam = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
		
	TeamProfile *aTeamProfileView = [[TeamProfile alloc] initWithNibName:@"TeamProfile" bundle:nil];
	aTeamProfileView.teamId = aTeam.teamId;
	[self.view addSubview:aTeamProfileView.view];
	
}

@end
